package com.nth.rooster.authentication.controllers;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/Authentication")
public class UploadDocuments {

	static Logger LOGGER = Logger.getLogger(UploadDocuments.class);

	/*
	 * Admin should upload the organization logo for the application users.
	 * 
	 * REF:
	 * http://www.journaldev.com/2573/spring-mvc-file-upload-example-tutorial
	 * -single-and-multiple-files
	 */
	@RequestMapping(value="/upload", method=RequestMethod.POST)
    public @ResponseBody String handleFileUpload(@RequestParam("name") String name,
            @RequestParam("file") MultipartFile file){
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(new File(name + "-uploaded")));
                stream.write(bytes);
                stream.close();
                return "You successfully uploaded " + name + " into " + name + "-uploaded !";
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + name + " because the file was empty.";
        }
    }
	
	@RequestMapping(value="/upload", method=RequestMethod.GET)
    public @ResponseBody String provideUploadInfo() {
        return "fileupload";
    }

	/*
	 * users can upload their profile picture
	 * 
	 * http://viralpatel.net/blogs/spring-mvc-multiple-file-upload-example/
	 */
	@RequestMapping(value = "/uploadProfileImage", method = RequestMethod.POST)
	public @ResponseBody
	String uploadProfileImageForUser(@RequestParam("name") String name,
			@RequestParam("file") MultipartFile file) {

		return "done";
	}

}
